package com.ruoyi.business.api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.google.common.collect.Maps;
import com.ruoyi.business.constants.Constant;
import com.ruoyi.business.enums.MapTypeEnums;
import com.ruoyi.business.service.CommonDataService;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.RedisUtils;
import com.ruoyi.common.utils.RestTemplateUtil;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClientException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

/**
 * @author liutao
 * @version 1.0
 * @description: TODO
 * @date 2024/4/10 21:24
 */
@Slf4j
@Controller
@RequestMapping("/api/arcgis")
public class MapServerApi {

    @Resource
    private CommonDataService commonDataService;
    @Resource
    private ISysConfigService configService;

    @Resource
    private TokenService tokenService;

//    @GetMapping("/MapServer")
//    public void transferArcgisData(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        String reqToken = RedisUtils.getCacheObject(Constant.ARCGIS_TOKEN);
//        if (StrUtil.isEmpty(reqToken)) {
//            reqToken = commonDataService.getArcgisTokens();
//        }
//        if (StrUtil.isEmpty(reqToken)) {
//            log.error("ArcGIS获取token失败。");
//            return;
//        }
//        Map<String, String[]> params = request.getParameterMap();
//        Map<String, Object> params1 = Maps.newHashMap();
//        String token = "", serverName = "";
//        for(String key : params.keySet()){
//            String[] a = params.get(key);
//            if(key.equals("token")){
//                token = a[0];
//            }else if(key.equals("serverName")){
//                serverName = a[0];
//            }else{
//                if(a != null && a.length > 0){
//                    params1.put(key, a[0]);
//                }
//            }
//        }
//        params1.put("token", reqToken);
//        String url = configService.selectConfigByKey(Constant.ARCGIS_SERVER_URL)+"/arcgis/rest/services/"+serverName+"/MapServer/export";
//
//        HttpResponse httpResponse =  HttpRequest.get(url).form(params1).execute();
//        InputStream inputStream = httpResponse.bodyStream();
//
//        response.setContentType("image/png");
//        byte[] buffer = new byte[1024];
//        int bytesread;
//        while((bytesread = inputStream.read(buffer)) != -1){
//            response.getOutputStream().write(buffer, 0, bytesread);
//        }
//        inputStream.close();
//        response.flushBuffer();
//    }

    @GetMapping("/MapServer")
    public void transferArcgisData(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String reqToken = RedisUtils.getCacheObject(Constant.ARCGIS_TOKEN);
        if (StrUtil.isEmpty(reqToken)) {
            reqToken = commonDataService.getArcgisTokens();
        }
        Map<String, String[]> params = request.getParameterMap();
        Map<String, String> params1 = Maps.newHashMap();
        String token = "", serverName = "", mapType = "";
        for (String key : params.keySet()) {
            String[] a = params.get(key);
            switch (key) {
                case "token":
                    token = a[0];
                    break;
                case "Authorization":
                    token = a[0];
                    break;
                case "serverName":
                    serverName = a[0];
                    break;
                case "mapType":
                    mapType = a[0];
                    break;
                default:
                    if (a != null && a.length > 0) {
                        params1.put(key, a[0]);
                    }
                    break;
            }
        }
        LoginUser user = tokenService.getLoginUser(token);
        if (user == null) {
            throw new ServiceException("用户获取失败！");
        }
        params1.put("token", reqToken);
        String server = "";
        if (mapType.equals(MapTypeEnums.FEATURE_SERVICE.getCode())) {
            int i = serverName.lastIndexOf("/");
            String start = serverName.substring(0, i);
            String end = serverName.substring(i + 1);
            server = start;
            params1.put("layers", "show:" + end);
        } else {
            server = serverName;
        }
        String url = configService.selectConfigByKey(Constant.ARCGIS_SERVER_URL) + "/arcgis/rest/services/" + server + "/MapServer/export";

        HttpResponse httpResponse = HttpRequest.get(url)
                .formStr(params1)
//                .body(JSONObject.toJSONString(params))
                .execute();
        response.setContentType("image/png");
        InputStream inputStream = httpResponse.bodyStream();
        byte[] buffer = new byte[1024];
        int bytesread;
        while ((bytesread = inputStream.read(buffer)) != -1) {
            response.getOutputStream().write(buffer, 0, bytesread);
        }
        inputStream.close();


        response.flushBuffer();
    }
}
